package leetcode.tree;

import java.util.*;

/**
 * 给你二叉树的根节点 root ，返回其节点值的 层序遍历 。 （即逐层地，从左到右访问所有节点）。
 * <p>
 * <p>
 * <p>
 * 示例 1：
 * <p>
 * <p>
 * 输入：root = [3,9,20,null,null,15,7]
 * 输出：[[3],[9,20],[15,7]]
 * 示例 2：
 * <p>
 * 输入：root = [1]
 * 输出：[[1]]
 * 示例 3：
 * <p>
 * 输入：root = []
 * 输出：[]
 * <p>
 * <p>
 * 提示：
 * <p>
 * 树中节点数目在范围 [0, 2000] 内
 * -1000 <= Node.val <= 1000
 */

public class LeetCode102_LevelOrder {
    public List<List<Integer>> levelOrder2(TreeNode root) {

        if (root == null) {
            return new ArrayList<>();
        }

        List<List<Integer>> r = new ArrayList<>();
        Map<TreeNode, Integer> nodeLevel = new HashMap<>();

        Queue<TreeNode> q = new LinkedList<>();
        q.add(root);
        nodeLevel.put(root, 0);

        while (!q.isEmpty()) {
            TreeNode curNode = q.poll();
            int level = nodeLevel.get(curNode);

            if (r.size() == level) {
                r.add(new ArrayList<>());
            }

            r.get(level).add(curNode.val);
            if (curNode.left != null) {
                q.add(curNode.left);
                nodeLevel.put(curNode.left, level + 1);
            }

            if (curNode.right != null) {
                q.add(curNode.right);
                nodeLevel.put(curNode.right, level + 1);
            }

        }

        return r;
    }

    /**
     * 树节点有限
     *
     * @param root
     * @return
     */
    public List<List<Integer>> levelOrder(TreeNode root) {
        if (root == null) {
            return new ArrayList<>();
        }
        TreeNode[] tn = new TreeNode[2001];
        int p = 0, q = 0, level = 0;
        int k, m;
        List<List<Integer>> r = new ArrayList<>();
        tn[q++] = root;

        while (p != q) {
            k = p;
            m = q;
            p = q;

            r.add(new ArrayList<>());
            for (int i = k; i < m; i++) {
                TreeNode curNode = tn[i];
                r.get(level).add(curNode.val);
                if (curNode.left != null) {
                    tn[q++] = curNode.left;
                }
                if (curNode.right != null) {
                    tn[q++] = curNode.right;
                }
            }
            level++;
        }
        return r;
    }
}
